import { BlockInputEvents, Layers, Node, Widget, instantiate, tween, Tween } from "cc";
import { ViewUtil } from "../../utils/ViewUtil";
import { ResLoader } from "../ResLoader";
import { Prefab } from "cc";

const ToastPrefabPath: string = 'common/toast';
const WaitPrefabPath: string = 'common/wait';
const UpDis: number = 140
/*
 * 滚动消息提示层
 */
export class LayerNotify extends Node {
    private black!: BlockInputEvents;
    /** 等待提示资源 */
    private wait: Node = null!;
    /** 自定义弹出提示内容资源 */
    private notifyItem: Prefab = null!;

    private twArr: { node: Node, tw: Tween<Node> }[] = []

    constructor(name: string) {
        super(name);

        var widget: Widget = this.addComponent(Widget);
        widget.isAlignLeft = widget.isAlignRight = widget.isAlignTop = widget.isAlignBottom = true;
        widget.left = widget.right = widget.top = widget.bottom = 0;
        widget.alignMode = 2;
        widget.enabled = true;
        this.init();
    }

    private async init() {
        this.layer = Layers.Enum.UI_2D;
        this.black = this.addComponent(BlockInputEvents);
        this.black.enabled = false;
        this.notifyItem = await ResLoader.Ins.loadAsync(ToastPrefabPath, Prefab)
    }

    /** 打开等待提示 */
    waitOpen() {
        if (this.wait == null) this.wait = ViewUtil.createPrefabNode(WaitPrefabPath);
        if (this.wait.parent == null) {
            this.wait.parent = this;
            this.black.enabled = true;
        }
    }

    /** 关闭等待提示 */
    waitClose() {
        if (this.wait.parent) {
            this.wait.parent = null;
            this.black.enabled = false;
        }
    }

    /**
     * 渐隐飘过提示
     * @param content 文本表示
     * @param useI18n 是否使用多语言
     */
    toast(content: string): void {

        let node = instantiate(this.notifyItem);
        const lab = node.getChildByName('lab')
        lab.uiLabel.string = content
        node.parent = this

        // this.changeAllToast()

        const tw = this.doTween(node, UpDis)
        // this.twArr.push({ node, tw })
    }

    // /** 显示中的toast向上移动 */
    // changeAllToast() {
    //     let index = this.twArr.length + 1
    //     for (const { node, tw } of this.twArr) {
    //         tw.stop()
    //         this.doTween(node, --index * UpDis)
    //     }
    // }

    /** towat动作 */
    doTween(notifyNode: Node, posY: number) {
        const tw = tween(notifyNode)
            .to(1, { y: posY }, { easing: 'quartOut' })
            .delay(0.5)
            .call(() => {
                const index = this.twArr.findIndex(v => v.tw == tw)
                this.twArr.splice(index, 1)
                notifyNode.destroy()
            })
            .start()

        return tw
    }

}